/* eslint-disable */
const { Controller } = require('egg');

class AccountController extends Controller {
  async login() {
    const { ctx, app } = this;
    const { username, password, status, userInputCode } = ctx.request.body
    const validateResult = await ctx.validate('user.login', ctx.request.body)
    if (!validateResult) return

    // 验证验证码
    try {
      const isCodeValid = await ctx.service.captcha.validateCode(username, userInputCode);

      if (!isCodeValid) {
        ctx.error('验证码错误');
        return;
      }

      const result = await ctx.service.user.login(username, password, status);
      if (result.success) {
        ctx.success(result.data, '登录成功');
      } else {
        ctx.error('用户名或密码不正确');
      }
    } catch (error) {
      // 捕获验证码错误
      console.error('验证码验证失败:', error);
      ctx.body = {
        message: error.message,
        newCaptcha: error.newCaptcha || null,
        expires_at: error.expires_at || null
      };
      ctx.status = 400;
    }
  }

  async register() {
    const { ctx } = this
    const user = ctx.request.body
    const valid = await ctx.service.user.checkUserNameValid(user.username)
    if (valid) {
      const result = await ctx.service.user.add(user)
      ctx.success(result, '用户注册成功')
    } else {
      ctx.error(`用户名为${user.username}的用户已存在,不能再注册!`)
    }
  }
  async logout() {
    const { ctx } = this;
    // 清除客户端存储的 token
    ctx.body = {
      success: true,
      message: '登出成功',
    };
  }
}
module.exports = AccountController; 